//
//  WPMineMyCollectionRecordVC.m
//  wobingwoyi
//
//  Created by WGP on 16/9/21.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPMineMyCollectionRecordVC.h"
#import "WPMineMyBoughtRecordCVC.h"
#import "WPMineMyCollectionRecordCVC.h"
#import "WPMRModel.h"
#import "WPCasesOfTheCollectionVC.h"
#import "WPMineLoginVC.h"
#import "SwipeBack.h"

@interface WPMineMyCollectionRecordVC ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)UIView *statusView;
@property(nonatomic,strong)UIView *navView;
@property(nonatomic,strong)UIView *titleView;
@property(nonatomic,strong)WPBtnNoHighLight *indivalBtn;
@property(nonatomic,strong)WPBtnNoHighLight *famousBtn;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)WPBtnNoHighLight *currentBtn;
@property(nonatomic,strong)UIView *sliderView;
@property(nonatomic,assign)CGFloat averageWidth;

@property(nonatomic,strong)WPMineMyCollectionRecordCVC *firstCell;
@property(nonatomic,strong)WPMineMyBoughtRecordCVC *secondCell;

@property(nonatomic,strong)NSMutableArray *collectRecordsArr;
@property(nonatomic,strong)NSMutableArray *boughtRecordsArr;

@end
@implementation WPMineMyCollectionRecordVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}


-(void)viewDidLoad
{
    [super viewDidLoad];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    self.view.backgroundColor = GlobalBgColor;
    [self setupUI];
    
    [self loadCollectRecordsData];
    [self loadBoughtRecordData];
}

-(void)loadCollectRecordsData
{
    
    //    加载收藏记录
    NSString *url = @"record/userCollections.do";
    NSDictionary *dict = @{@"page":@(0)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            if ([responseDict[@"detail"] count])
            {
                
                for (NSDictionary *dict in responseDict[@"detail"])
                {
                    [self.collectRecordsArr addObject:[WPMRModel yy_modelWithDictionary:dict]];
                }
            }
            self.firstCell.collectRecordsArr = self.collectRecordsArr;
            
            [self dismiss];
        }
        else
        {
            [self showErrorInfoWithStatus:@"加载失败"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
        
    }];
}

-(void)loadBoughtRecordData
{
    [self showWithStatus:@"正在加载"];
    //    加载收藏记录
    NSString *url = @"user/payForRecord.do";
    NSDictionary *dict = @{@"page":@(0)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            if ([responseDict[@"detail"] count])
            {
                
                for (NSDictionary *dict in responseDict[@"detail"])
                {
                   WPMRModel *model = [WPMRModel yy_modelWithDictionary:dict];
                    if (model)
                    {
                        [self.boughtRecordsArr addObject:model];
                    }
                }
            }
            self.secondCell.collectRecordsArr = self.boughtRecordsArr;
            
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"加载失败"];
            }
        }
        
        [self dismiss];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
        
    }];
}

//重新登陆的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        WPMineLoginVC *vc = [WPMineLoginVC new];
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
        
        vc.successLoginBlock = ^
        {
            NSString *url = @"user/payForRecord.do";
            NSDictionary *dict = @{@"page":@(0)};
            
            [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
                
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                
                NSDictionary *responseDict = (NSDictionary *)responseObject;
                if ([responseDict[@"result"] isEqualToString:@"success"])
                {
                    if ([responseDict[@"detail"] count])
                    {
                        
                        for (NSDictionary *dict in responseDict[@"detail"])
                        {
                            WPMRModel *model = [WPMRModel yy_modelWithDictionary:dict];
                            if (model)
                            {
                                [self.boughtRecordsArr addObject:model];
                            }
                        }
                    }
                    self.secondCell.collectRecordsArr = self.boughtRecordsArr;
                    [self dismiss];
                    
                }
                else
                {
                    [self showErrorInfoWithStatus:@"加载失败"];
                }
                
               
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [self showErrorInfoWithStatus:@"网络错误"];
                
            }];
            
            [self loadCollectRecordsData];
        };
    }
}

-(NSMutableArray *)collectRecordsArr
{
    if (_collectRecordsArr == nil)
    {
        _collectRecordsArr = [NSMutableArray array];

    }
    return _collectRecordsArr;
}

-(NSMutableArray *)boughtRecordsArr
{
    if (_boughtRecordsArr == nil)
    {
        _boughtRecordsArr = [NSMutableArray array];
    }
    return _boughtRecordsArr;
}

-(void)setupUI
{
    [self statusView];
    [self navView];
    [self titleView];
    [self collectionView];
}

-(UIView *)statusView
{
    if (_statusView == nil)
    {
        _statusView = [UIView new];
        _statusView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_statusView];
        
        [_statusView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.height.mas_equalTo(20);
        }];
    }
    return _statusView;
}

-(UIView *)navView
{
    if (_navView == nil)
    {
        _navView = [UIView new];
        _navView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_navView];
        
        [_navView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.statusView.mas_bottom);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(44);
        }];
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelBtn setBackgroundImage:[UIImage imageNamed:@"back_normal"] forState:UIControlStateNormal];
        [cancelBtn setBackgroundImage:[UIImage imageNamed:@"back_highlight"] forState:UIControlStateHighlighted];
        [cancelBtn addTarget:self action:@selector(cancelBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [cancelBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_navView addSubview:cancelBtn];
        
        UILabel *titleLabel = [UILabel new];
        titleLabel.text = @"我的收藏";
        titleLabel.textColor = GLobalFontColor;
        titleLabel.font = [UIFont systemFontOfSize:18];
        [_navView addSubview:titleLabel];
        
        UIImageView *lineImageView = [self lineImageView];
        [_navView addSubview:lineImageView];
        
        [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_navView);
            make.left.equalTo(_navView).offset(12);
        }];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(_navView);
        }];
        
        [lineImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0.5);
            make.left.right.bottom.equalTo(_navView);
        }];
    }
    return _navView;
}

-(UIView *)titleView
{
    if (_titleView == nil)
    {
        _titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 44)];
        _titleView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_titleView];
        
        self.indivalBtn = [self buttonWith:@"已购病例"];
        self.currentBtn = self.indivalBtn;
        self.currentBtn.selected = YES;
        self.famousBtn = [self buttonWith:@"收藏记录"];
        
        [_titleView addSubview:self.indivalBtn];
        [_titleView addSubview:self.famousBtn];
        
        UIImageView *lineView = [UIImageView new];
        lineView.backgroundColor = GLobalLineColor;
        [_titleView addSubview:lineView];
        
        CGFloat titleWidth = [self.indivalBtn.titleLabel.text sizeWithMaxSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) font:15].width + [self.famousBtn.titleLabel.text sizeWithMaxSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) font:15].width;
        self.averageWidth = (SCREEN_WIDTH-titleWidth)/3;
        
        [self.indivalBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_titleView);
            make.left.equalTo(_titleView).offset(self.averageWidth);
        }];
        
        [self.famousBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_titleView);
            make.right.equalTo(_titleView).offset(-self.averageWidth);
        }];
        
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0.5);
            make.left.right.bottom.equalTo(_titleView);
        }];
        
        self.sliderView = [[UIView alloc] initWithFrame:CGRectMake(self.averageWidth, _titleView.bounds.size.height-1.5, titleWidth*0.5, 1.5)];
        self.sliderView.backgroundColor = GlobalColor;
        [_titleView addSubview:self.sliderView];
        
    }
    return _titleView;
}

-(UICollectionView *)collectionView
{
    if (_collectionView == nil)
    {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemH = SCREEN_HEIGHT-CGRectGetMaxY(self.titleView.frame);
        layout.itemSize = CGSizeMake(SCREEN_WIDTH, itemH);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.titleView.frame), SCREEN_WIDTH, itemH) collectionViewLayout:layout];
        _collectionView.backgroundColor = GlobalBgColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.bounces = 0;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        
        [_collectionView registerClass:[WPMineMyCollectionRecordCVC class] forCellWithReuseIdentifier:@"WPMineMyCollectionRecordCVC"];
        [_collectionView registerClass:[WPMineMyBoughtRecordCVC class] forCellWithReuseIdentifier:@"WPMineMyBoughtRecordCVC"];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

#pragma mark - 数据源方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 2;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == 0)
    {
        
        WPMineMyBoughtRecordCVC *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WPMineMyBoughtRecordCVC" forIndexPath:indexPath];
        self.secondCell = cell;
        cell.collectRecordsArr = self.boughtRecordsArr;
        cell.noRecordStr = @"暂无购买记录";
        
        __weak typeof(self) weakSelf = self;
        cell.cellDidClickBlock = ^(WPMRModel *model)
        {
            
            WPCasesOfTheCollectionVC *rirVC = [WPCasesOfTheCollectionVC new];
            rirVC.model = model;
            [weakSelf.navigationController pushViewController:rirVC animated:YES];
            
        };
        
        return cell;
    }
    else
    {
        WPMineMyCollectionRecordCVC *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WPMineMyCollectionRecordCVC" forIndexPath:indexPath];
        self.firstCell = cell;
        cell.collectRecordsArr = self.collectRecordsArr;
        
        __weak typeof(self) weakSelf = self;
        cell.cellDidClickBlock = ^(WPMRModel *model)
        {
            
            WPCasesOfTheCollectionVC *rirVC = [WPCasesOfTheCollectionVC new];
            rirVC.model = model;
            [weakSelf.navigationController pushViewController:rirVC animated:YES];
            
        };
        return cell;
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger indexPage = scrollView.contentOffset.x/scrollView.bounds.size.width;
    
    if (indexPage == 0)
    {
        [self titleBtnDidClick:self.indivalBtn];
    }
    else
    {
        [self titleBtnDidClick:self.famousBtn];
    }
}

-(WPBtnNoHighLight *)buttonWith:(NSString *)title
{
    WPBtnNoHighLight *btn = [WPBtnNoHighLight buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:GloballightFontColor forState:UIControlStateNormal];
    [btn setTitleColor:GLobalFontColor forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(titleBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    return btn;
}

-(void)titleBtnDidClick:(WPBtnNoHighLight *)btn
{
    if (self.currentBtn == btn)
    {
        return ;
    }
    self.currentBtn.selected = NO;
    self.currentBtn = btn;
    self.currentBtn.selected = YES;
    
    if (btn == self.indivalBtn)
    {
        [UIView animateWithDuration:sliderViewAnimationTime animations:^{
            
            self.sliderView.transform = CGAffineTransformIdentity;
        }];
        
        [self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    else
    {
        [UIView animateWithDuration:sliderViewAnimationTime animations:^{
            
            self.sliderView.transform = CGAffineTransformMakeTranslation(CGRectGetMinX(self.famousBtn.frame)-self.averageWidth, 0);
        }];
        
        [self.collectionView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:YES];
    }
}

-(void)cancelBtnDidClick:(UIButton *)btn
{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self.navigationController popViewControllerAnimated:YES];
}

-(UIImageView *)lineImageView
{
    UIImageView *imageView = [UIImageView new];
    imageView.backgroundColor = GLobalLineColor;
    
    return imageView;
}

-(void)dealloc
{
//    NSLog(@"我的收藏控制器死了");
}

@end
